package com.auto.survey.widget

import android.content.Context
import android.content.res.ColorStateList
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.auto.survey.R

class CommonTitle @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr) {
    private var mTitle_leftIcon: ImageView? = null
    private var mTitle_centerText: TextView? = null
    private var mTitle_rightText: TextView? = null
    private var mCommon_title: ConstraintLayout? = null

    companion object {
        val TEXT_POSITON_CENTER = 0X1001
        val TEXT_POSITON_RIGHT= 0X1002
    }


    init {
        // 初始化代码（加载布局、设置属性等）
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        LayoutInflater.from(context).inflate(R.layout.common_title, this, true);
        mCommon_title = findViewById<View>(R.id.Common_title) as ConstraintLayout //根布局
        mTitle_leftIcon = findViewById<View>(R.id.title_leftIcon) as ImageView //左边图片
        mTitle_centerText = findViewById<View>(R.id.title_centerText) as TextView //中间文字
        mTitle_rightText = findViewById(R.id.title_rightText)
    }

    fun setTitle(title: String?) {
        if (!TextUtils.isEmpty(title)) {
            mTitle_centerText?.text = title
            mTitle_centerText?.visibility = VISIBLE
        }
    }


    fun setRightTitle(title: String?) {
        if (!TextUtils.isEmpty(title)) {
            mTitle_rightText?.text = title
            mTitle_rightText?.visibility = VISIBLE
        }
    }

    fun setTitleColor(colorRes:Int, position:Int) {

        if (position == TEXT_POSITON_CENTER){
            mTitle_centerText?.setTextColor(colorRes)
        }else if (position == TEXT_POSITON_RIGHT) {
            mTitle_rightText?.setTextColor(colorRes)
        }

    }

    /**
     * 设置背景色
     * @param backgroundResource
     */
    override fun setBackgroundResource(backgroundResource: Int) {
        mCommon_title?.setBackgroundResource(backgroundResource)
    }

    fun setOnBackListener(listener: OnClickListener?) {
        mTitle_leftIcon?.setOnClickListener(listener)
    }

    fun setOnRightTextClickListener(listener: OnClickListener?){
        mTitle_rightText?.setOnClickListener(listener)
    }

    fun setLeftIcon(res:Int) {
        mTitle_leftIcon?.setImageResource(res)
    }

    fun  setLeftIconVisible(visible:Int) {
        mTitle_leftIcon?.visibility = visible;
    }

    fun setLeftIconColor(colorRes:Int) {
        val colorStateList = ColorStateList.valueOf(ContextCompat.getColor(context, colorRes))
        mTitle_leftIcon?.drawable?.setTintList(colorStateList)
    }

}